package com.jiu345.utils;

import com.jiu345.api.pojo.GoodsCategory;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * package:DeptNodeUtil
 * @author MrLei QQ:235921049
 * @date 2024-05-21
 * desc:层级商品分类工具类
 */
public class GoodsCateNodeUtil {
    public static List<GoodsCategory> buildTree(List<GoodsCategory> goodsCateList) {
        //创建list集合，用于封装最终的数据
        List<GoodsCategory> trees = new ArrayList<>();
        //遍历所有菜单集合
        for (GoodsCategory goodsCate : goodsCateList) {
            //取第一层菜单
            if (goodsCate.getParentId() == 0) {
                //使用递归，查找下一级
                trees.add(findChildren(goodsCate, goodsCateList));
            }
        }
        return trees;
    }

    public static GoodsCategory findChildren(GoodsCategory goodsCate, List<GoodsCategory> goodsCateList) {
        //初始化children
        goodsCate.setChildren(new ArrayList<>());
        //递归查询
        for(GoodsCategory it:goodsCateList){
            //判断id和parentId是否相同
            if(Objects.equals(goodsCate.getId(), it.getParentId())){
                //it就是下层数据，进行封装
                goodsCate.getChildren().add(findChildren(it,goodsCateList));
            }
        }
        return goodsCate;
    }
}
